package com.xx.job.service.server.impl;

import com.xx.job.common.util.OsAndBrowserInfoUtil;
import com.xx.job.entity.server.*;
import com.xx.job.service.server.ServerService;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class ServerServiceImpl implements ServerService {

    Sigar sigar = new Sigar();
    @Override
    public Cpu getCpu() throws SigarException {
        Cpu cpu = new Cpu();

        org.hyperic.sigar.CpuInfo[] cpuInfos = sigar.getCpuInfoList();
        long cpunum = cpuInfos.length;
        cpu.setCpuNum(cpunum);
        CpuPerc cpuPerc = sigar.getCpuPerc();
        cpu.setPercent(cpuPerc.getUser());

        List<CpuInfo> cpuInfo = new ArrayList<>();
        for (int i = 0; i < cpuInfos.length; i++) {// 不管是单块CPU还是多CPU都适用
            org.hyperic.sigar.CpuInfo info = cpuInfos[i];
            CpuInfo cInfo = new CpuInfo();
            cInfo.setCacheSize(info.getCacheSize());
            cInfo.setModelName(info.getModel());
            cInfo.setCpu(i+1L);
            cInfo.setMhz(info.getMhz());
            cInfo.setVendorId(info.getVendor());
            cpuInfo.add(cInfo);
        }
        cpu.setCpuInfo(cpuInfo);

        return cpu;
    }

    @Override
    public Disk getDisk() throws SigarException {
        // 物理内存信息
        org.hyperic.sigar.Mem sMem = sigar.getMem();
        Mem mem = new Mem();
        Disk disk = new Disk();
        disk.setTotal(sMem.getTotal() / 1024L / 1024);
        disk.setFree(sMem.getFree() / 1024L / 1024);
        return disk;
    }

    @Override
    public org.hyperic.sigar.Mem getMem() throws SigarException {
        return sigar.getMem();
    }

    @Override
    public Os getOs(HttpServletRequest request) {
        OsAndBrowserInfoUtil osAndBrowserInfoUtil = new OsAndBrowserInfoUtil(request);
        String ip = osAndBrowserInfoUtil.getIp();
        Os os = new Os();
        os.setIp(ip);
        os.setGoOs(osAndBrowserInfoUtil.getOs());
        os.setVersion("jdk1.8");
        os.setArch("SAAS");
        os.setCompiler("Tomcat");
        os.setProjectDir("www.javaadmin");
        os.setNumGoroutine(20L);
        return os;
    }
}
